import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:sui_shou_pai/Utils/storage_util.dart';
import 'package:sui_shou_pai/camera/alert_person.dart';
import 'package:sui_shou_pai/camera/model/Location.dart';
import 'package:sui_shou_pai/camera/model/department.dart';
import 'package:sui_shou_pai/chat/init/interface.dart';
import 'package:sui_shou_pai/module/color.dart';
import 'package:sui_shou_pai/network/http_request.dart';

import 'LocationPage.dart';
import 'image_view.dart';

class CameraPage extends StatefulWidget {
  final String image;

  CameraPage({Key key, this.image}) : super(key: key);

  @override
  _CameraPageState createState() => _CameraPageState();
}

class _CameraPageState extends State<CameraPage> {
  TextEditingController textEditingController;
  FocusNode _textFocusNode = new FocusNode();
  ImageGridState _imgState;
  String type;
  String photoRecordId = "";
  Department choice;
  Location location;

  @override
  void initState() {
    super.initState();
    _imgState = ImageGridState();
    textEditingController = new TextEditingController();
    type = "";
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Scaffold(
        appBar: AppBar(
          title: Text("分享图片"),
          centerTitle: true,
          actions: [
            IconButton(
                onPressed: () {
                  // print(_imgState.images[0].path);
                  // _image._state.
                  _submitphoto();
                },
                icon: Icon(Icons.check_outlined))
          ],
        ),
        body: ListView(
          children: [
            Padding(
              padding: EdgeInsets.only(left: 40, right: 40, top: 20),
              child: TextField(
                controller: textEditingController,
                focusNode: _textFocusNode,
                cursorColor: Colors.grey,
                cursorHeight: 25,
                maxLines: null,
                decoration: InputDecoration(
                    hintText: '这一刻的想法...',
                    hintStyle: TextStyle(color: Colors.grey, fontSize: 18),
                    enabledBorder: UnderlineInputBorder(
                      borderSide: BorderSide(color: Colors.white),
                    ),
                    border: InputBorder.none),
                style: TextStyle(color: Color(0xFF03073C), fontSize: 18),
              ),
            ),
            SizedBox(
              height: 20,
            ),
            ImageGridWidget(image: widget.image, myState: _imgState),
            SizedBox(
              height: 35,
            ),
            Divider(
                height: 1.0, indent: 40.0, endIndent: 40.0, color: greyCCCCCC),
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              child: Container(
                padding: EdgeInsets.only(left: 50, top: 20, bottom: 20),
                child: Row(
                  children: [
                    type == ""
                        ? Icon(
                            Icons.photo_camera_back,
                            color: Colors.black54,
                            size: 25,
                          )
                        : type == "环境分享"
                            ? Icon(
                                Icons.share,
                                color: Colors.green,
                                size: 25,
                              )
                            : Icon(
                                Icons.cleaning_services,
                                color: Colors.red,
                                size: 25,
                              ),
                    Padding(
                      padding: EdgeInsets.only(left: 20, right: 180),
                      child: type == ""
                          ? Text("图片类型", style: TextStyle(fontSize: 20))
                          : type == "环境整改"
                              ? Text(type,
                                  style: TextStyle(
                                      fontSize: 20, color: Colors.red))
                              : Text(type,
                                  style: TextStyle(
                                      fontSize: 20, color: Colors.green)),
                    ),
                    Icon(Icons.arrow_forward_ios_rounded, color: Colors.black54)
                  ],
                ),
              ),
              onTap: () {
                showCupertinoModalPopup(
                  context: context,
                  builder: (context) {
                    return CupertinoActionSheet(
                      title: Text(
                        '图片类型',
                        style: TextStyle(fontSize: 22),
                      ), //标题
                      message: Text('请选择图片类型'), //提示内容
                      actions: <Widget>[
                        //操作按钮集合
                        CupertinoActionSheetAction(
                          onPressed: () {
                            Navigator.pop(context);
                            setState(() {
                              type = '环境分享';
                              print(type);
                            });
                            _textFocusNode.unfocus();
                          },
                          child: Text('环境分享'),
                        ),
                        CupertinoActionSheetAction(
                          onPressed: () {
                            setState(() {
                              type = '环境整改';
                              print(type);
                            });
                            Navigator.pop(context);
                          },
                          child: Text('环境整改'),
                        ),
                      ],
                      cancelButton: CupertinoActionSheetAction(
                        //取消按钮
                        onPressed: () {
                          Navigator.pop(context);
                        },
                        child: Text('取消'),
                      ),
                    );
                  },
                );
              },
            ),
            Divider(
                height: 1.0, indent: 40.0, endIndent: 40.0, color: greyCCCCCC),
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              child: Container(
                padding: EdgeInsets.only(left: 50, top: 20, bottom: 20),
                child: Row(
                  children: [
                    Icon(
                      Icons.location_on_outlined,
                      color: location == null ? Colors.black54 : Colors.green,
                      size: 25,
                    ),
                    Expanded(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Padding(
                            padding: EdgeInsets.only(left: 20),
                            child: location == null
                                ? Text("所在位置", style: TextStyle(fontSize: 20))
                                : Text(location.name,
                                    style: TextStyle(
                                        fontSize: 20, color: Colors.green)),
                          ),
                          Padding(
                              padding: EdgeInsets.only(right: 50),
                              child: Icon(Icons.arrow_forward_ios_rounded,
                                  color: Colors.black54))
                        ],
                      ),
                    )
                  ],
                ),
              ),
              onTap: () {
                Navigator.push(
                    context,
                    new MaterialPageRoute(
                        builder: (context) => LocationPage())).then((value) {
                  setState(() {
                    location = value;
                  });
                  _textFocusNode.unfocus();
                });
              },
            ),
            Divider(
                height: 1.0, indent: 40.0, endIndent: 40.0, color: greyCCCCCC),
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              child: Container(
                padding: EdgeInsets.only(left: 50, top: 20, bottom: 20),
                child: Row(
                  children: [
                    Icon(Icons.alternate_email,
                        color: choice == null ? Colors.black54 : Colors.green),
                    Expanded(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Padding(
                            padding: EdgeInsets.only(left: 20),
                            child: choice == null
                                ? Text("提醒谁看", style: TextStyle(fontSize: 20))
                                : Text(
                                    "${choice.name}:  ${choice.employee.name}",
                                    style: TextStyle(
                                        fontSize: 20, color: Colors.green)),
                          ),
                          Padding(
                              padding: EdgeInsets.only(right: 50),
                              child: Icon(Icons.arrow_forward_ios_rounded,
                                  color: Colors.black54))
                        ],
                      ),
                    )
                  ],
                ),
              ),
              onTap: () {
                Navigator.push(
                    context,
                    new MaterialPageRoute(
                        builder: (context) => AlertPersonPage())).then((value) {
                  setState(() {
                    choice = value;
                  });
                  _textFocusNode.unfocus();
                });
              },
            ),
            Divider(
                height: 1.0, indent: 40.0, endIndent: 40.0, color: greyCCCCCC),
          ],
        ),
      ),
      onTap: () {
        hindKeyBoarder();
      },
    );
  }

  void hindKeyBoarder() {
    //输入框失去焦点
    _textFocusNode.unfocus();
    //隐藏键盘
    SystemChannels.textInput.invokeMethod('TextInput.hide');
  }

  void _submitphoto() async {
    Dio dio = Dio();
    List<File> list = [];
    for (int i = 0; i < _imgState.images.length; i++) {
      list.add(File(_imgState.images[i].path));
    }
    List<MultipartFile> filelist = [];
    for (int i = 0; i < list.length; i++) {
      MultipartFile test =
          MultipartFile.fromFileSync(list[i].path, filename: "image.png");
      filelist.add(test);
    }
    String text = textEditingController.text;
    String photo_type = type;
    String employeeId = await StorageUtil.getStringItem("employeeId");
    textEditingController.clear();

    var formData = FormData.fromMap({
      "files": filelist,
      "content": text,
      "employeeId": employeeId,
      "type": photo_type,
      "responsibleId": choice == null ? "" : choice.employee.employeeId,
      "location": location == null ? "" : location.name
    });
    if(photo_type == '环境整改' && choice==null){
      Fluttertoast.showToast(msg: "请@负责人");
    }else{
      HttpRequest.request("/photo-record/addPhotoRecord",
          method: "post",
          data: formData,
          token: await StorageUtil.getStringItem("token"))
          .then((value) {
        print(value);
        if (value.data["code"] == 200) {
          setState(() {
            photoRecordId = value.data["result"].toString();
          });
          Fluttertoast.showToast(msg: "发布成功");
        } else {
          Fluttertoast.showToast(msg: "发布失败");
        }
      });

      if(photo_type=="环境整改"){
        Future.delayed(Duration(milliseconds: 1200), () {
          ChatInterface.addRecord(
              "$photoRecordId#这里的环境需要整改了", choice.employee.id.toString());
          setState(() {
            type = "";
            choice = null;
          });
          Navigator.pop(context);
        });
      }else{
        Future.delayed(Duration(milliseconds: 1200), () {
          setState(() {
            type = "";
            choice = null;
          });
          Navigator.pop(context);
        });
      }
    }
    }
}
